package com.qfedu.psys.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.qfedu.common.WoException;
import com.qfedu.common.exception.handler.WoControllerExceptionHandler;
import com.qfedu.common.util.WoUtil;
import com.qfedu.psys.dto.MenuDto;
import com.qfedu.psys.dto.WoUser;
import com.qfedu.psys.service.CoreService;
import com.qfedu.psys.service.UserService;
import com.qfedu.psys.util.PSysConstant;
import com.qfedu.psys.util.PSysUtil;

@Controller
@SessionAttributes(names = PSysConstant.SESSION_USER)
public class MainController {

	private final static Logger LOG = LogManager.getLogger(MainController.class);

	@Resource
	private CoreService coreService;

	@Resource
	private WoControllerExceptionHandler exceptionHandler;

	@RequestMapping("/")
	public String toHome(Map<String, Object> map) {
		return exceptionHandler.toLoginView(() -> {
			WoUser u = PSysUtil.getCurrentUser(map);
			List<MenuDto> menus = coreService.getMenus(u, null, null);
			map.put("menus", menus);
		}, map, "main");
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String toLogin(String error, Map<String, Object> map) {
		if (!WoUtil.isEmpty(error)) {
			map.put("error", error);
		}
		return "login";
	}

	@Resource
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String toLogin(String username, String password, String roleId, Map<String, Object> map) {
		try {
			WoUser u = coreService.authenticate(username, password, roleId);
			map.put(PSysConstant.SESSION_USER, u);
			if (u.getPasswordTime() == null) {
				return "redirect:/sys/password?" + WoControllerExceptionHandler.getErrorQueryString("您还没有修改过密码，请修改！");
			}
			return "redirect:/";
		} catch (WoException e) {
			LOG.error(e.getMessage(), e);
			map.put(WoControllerExceptionHandler.MSG_KEY_FAIL, e.getMessage());
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			map.put(WoControllerExceptionHandler.MSG_KEY_FAIL, "未知异常！");
		}
		return "login";
	}

	/**
	 * @param error
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/sys/password", method = RequestMethod.GET)
	public String password(String error, Map<String, Object> map) {
		// UserDto u = (UserDto) map.get(PSysConstant.SESSION_USER);
		map.put(WoControllerExceptionHandler.MSG_KEY_FAIL, error);
		return "sys/password";
	}
	
	@RequestMapping(value = "/logout")
	public String logout(Map<String, Object> map, SessionStatus sessionStatus) {
		map.remove(PSysConstant.SESSION_USER);
		sessionStatus.setComplete();
		return "redirect:/login";
	}
}
